#include "stdafx.h"
#include "UtilStr.h"
#include "MD5.h"

namespace Util
{
	std::string UtilStr::utf8_to_gbk(const char* src)
	{
		// UTF8 to Unicode
		int len = MultiByteToWideChar(CP_UTF8, 0, src, -1, NULL, 0);
		WCHAR *wszGBK = new WCHAR[len + 1];
		memset(wszGBK, 0, sizeof(WCHAR) * (len + 1));
		MultiByteToWideChar(CP_UTF8, 0, src, -1, wszGBK, len);

		// Unicode to GBK
		len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
		char *szGBK = new char[len + 1];
		memset(szGBK, 0, len + 1);
		WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
		
		std::string strRet(szGBK);
		delete[] wszGBK;
		delete[] szGBK;

		return strRet;
	}

	std::string UtilStr::gbk_to_utf8(const char* src)
	{
		// GBK to Unicode
		int len = MultiByteToWideChar(CP_ACP, 0, src, -1, NULL, 0);
		WCHAR *wszUtf8 = new WCHAR[len + 1];
		memset(wszUtf8, 0, sizeof(WCHAR) * (len + 1));
		MultiByteToWideChar(CP_ACP, 0, src, -1, wszUtf8, len);

		// Unicode to UTF8
		len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
		char *szUtf8 = new char[len + 1];
		memset(szUtf8, 0, len + 1);
		WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)wszUtf8, -1, (LPSTR)szUtf8, len, NULL, NULL);

		std::string strRet(szUtf8);
		delete[] wszUtf8;
		delete[] szUtf8;

		return strRet;
	}

	std::wstring UtilStr::char_to_wchar(const char* src)
	{
		int len = MultiByteToWideChar(CP_ACP, 0, src, -1, NULL, 0);
		WCHAR *wszBuf = new WCHAR[len + 1];
		memset(wszBuf, 0, sizeof(WCHAR) * (len + 1));
		MultiByteToWideChar(CP_ACP, 0, src, -1, wszBuf, len);

		std::wstring strRet(wszBuf);
		delete[] wszBuf;

		return strRet;
	}
	std::string UtilStr::wchar_to_char(const WCHAR* src)
	{
		int len = WideCharToMultiByte(CP_ACP, 0, src, -1, NULL, 0, NULL, NULL);
		char *szBuf = new char[len + 1];
		memset(szBuf, 0, len + 1);
		WideCharToMultiByte(CP_ACP, 0, src, -1, szBuf, len, NULL, NULL);

		std::string strRet(szBuf);
		delete[] szBuf;

		return strRet;
	}

	std::string UtilStr::md5_digest_str(const char* src)
	{
		CMd5 md5;
		md5.TargetStr(src);
		return md5.GetDigestKey();
	}

	std::string UtilStr::md5_digest_file(const char* file_path)
	{
		CMd5 md5;
		md5.TargetFile(file_path);
		return md5.GetDigestKey();
	}

	void UtilStr::split_str(const char* src, const char split, std::vector<std::string> &out)
	{
		int iLoop = 0;
		int pre = 0;
		while (src[iLoop] != '\0')
		{
			if (src[iLoop] == split)
			{
				if (pre != iLoop)
					out.push_back(std::string(src, pre, iLoop - pre));
				pre = iLoop + 1;
			}
			iLoop++;
		}
		if (pre != iLoop)
			out.push_back(std::string(src, pre, iLoop - pre));
	}
}